<template>
  <div id="show-blog" class="show-blog">
    <div class="title">
      <h1>博客总览</h1>
    </div>
    <div class="search">
      <input type="text" placeholder="搜索..." v-model="search">
    </div>
    <div class="blogs">
      <ul>
        <!--因为使用了搜索方法，不再从blogs里遍历，而是filteredBlogs-->
        <li class="single-blog" v-for="blog in filteredBlogs">
          <router-link v-bind:to="'/blog/' + blog.id">
            <h4>{{ blog.title | upperCase }}</h4>
          </router-link>
          <article>{{ blog.content | snippet }}</article>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
  import Axios from 'axios'

  export default {
    name: 'show-blog',
    data() {
      return {
        blogs: [],
        search: ''
      }
    },
    created: function () {
      // 如果要使用本地的数据，必须放在static目录下
      Axios.get('/posts.json')
          .then(function (res) {
            // 返回的res是json格式，需要进行解析
            return res.data;
          }).then((res) => {
                var blogsArray = [];
                for (let key in res) {
                  res[key].id = key;
                  blogsArray.push(res[key]);
                }
                this.blogs = blogsArray;
            })
    },
    computed: {
      filteredBlogs: function () {
        // 箭头函数
        return this.blogs.filter((blog) => {
          // 搜索时去除空格
          var matchTitle = blog.title.replace(' ','').match(this.search.replace(' ',''));
          var matchBody = blog.content.replace(' ','').match(this.search.replace(' ',''));
          return matchTitle || matchBody;
        })
      }
    }
  }

</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less" src="./ShowBlogs.less"></style>
